package com.viphuli.app.tool.handler;

import java.text.SimpleDateFormat;
import java.util.List;

import android.graphics.drawable.Drawable;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.ButterKnife;

import com.offroader.utils.ViewUtils;
import com.viphuli.app.tool.R;
import com.viphuli.app.tool.adapter.HomeMemberAdapter;
import com.viphuli.app.tool.bean.page.HomePage;
import com.viphuli.app.tool.bean.part.AccountUser;
import com.viphuli.app.tool.bean.part.ArrangeInfo;
import com.viphuli.app.tool.bean.part.ArrangeRecord;
import com.viphuli.app.tool.common.AccessTokenKeeper;
import com.viphuli.app.tool.common.Constants.ArrangeRecordType;
import com.viphuli.app.tool.common.Constants.UserType;
import com.viphuli.app.tool.common.MyApp;
import com.viphuli.app.tool.fragment.AccountFragment;
import com.viphuli.app.tool.fragment.CircleMemberFragment;
import com.viphuli.app.tool.fragment.CircleUserAddFragment;
import com.viphuli.app.tool.fragment.HomeFragment;
import com.viphuli.app.tool.utils.ImageUtils;
import com.viphuli.app.tool.utils.OtherUtils;

public class HomeResponseHandler extends MyBaseHttpResponseHandler<HomeFragment, HomePage> implements OnItemClickListener, OnClickListener {

	@Override
	public void onStart() {
		super.onStart();

		//排班记录
		caller.getRecordView().setVisibility(View.GONE);
		caller.getRecordEmptyView().setVisibility(View.VISIBLE);

		//我的排班 
		caller.getArrangeView().setVisibility(View.GONE);
		caller.getArrangeEmptyView().setVisibility(View.VISIBLE);

		//小组成员
		caller.getUserView().setVisibility(View.GONE);
		caller.getUserEmptyView().setVisibility(View.VISIBLE);

	}

	@Override
	public void deal() {

		//处理排班记录
		dealArrangeRecord();

		//处理我的排班
		dealMyArrange();

		//小组成员
		circleMember();

		//当用户为管理员的时候
		AccountUser user = page.getUser();
		if (user != null && UserType.arrange_admin.getValue() == user.getUserType()) {

			caller.getArrangeBtnLayout().setVisibility(View.VISIBLE);
			MenuItem menuItem = caller.getMenu().findItem(R.id.id_menu_home_right_member_holiday);
			if (menuItem != null)
				menuItem.setVisible(true);

			//设置左图标
			Drawable drawableLeft = MyApp.getInstance().getResources().getDrawable(R.drawable.ic_home_item_arrange_recent);
			/// 这一步必须要做,否则不会显示.  
			drawableLeft.setBounds(0, 0, drawableLeft.getMinimumWidth(), drawableLeft.getMinimumHeight());

			caller.getArrangeLayout().setCompoundDrawables(drawableLeft, null, null, null);

		} else {

			caller.getArrangeBtnLayout().setVisibility(View.GONE);
			MenuItem menuItem = caller.getMenu().findItem(R.id.id_menu_home_right_member_holiday);
			if (menuItem != null)
				menuItem.setVisible(false);

			//设置右箭头
			Drawable drawableRight = MyApp.getInstance().getResources().getDrawable(R.drawable.sl_btn_right_arrow);
			/// 这一步必须要做,否则不会显示.  
			drawableRight.setBounds(0, 0, drawableRight.getMinimumWidth(), drawableRight.getMinimumHeight());

			//设置左图标
			Drawable drawableLeft = MyApp.getInstance().getResources().getDrawable(R.drawable.ic_home_item_arrange_recent);
			/// 这一步必须要做,否则不会显示.  
			drawableLeft.setBounds(0, 0, drawableLeft.getMinimumWidth(), drawableLeft.getMinimumHeight());

			caller.getArrangeLayout().setCompoundDrawables(drawableLeft, null, drawableRight, null);

		}

	}

	/**
	 * 排班记录
	 */
	private void dealArrangeRecord() {

		//传递数据到Fragment
		caller.setArrangeRecordInfoList(page.getArrangeRecordInfoList());

		List<ArrangeRecord> recordList = page.getArrangeRecordInfoList();

		if (recordList != null && !recordList.isEmpty()) {
			caller.getRecordEmptyView().setVisibility(View.GONE);
			caller.getRecordView().setVisibility(View.VISIBLE);

			View recordView = caller.getRecordView();
			recordView.setOnClickListener(this);

			//排班记录对象
			ArrangeRecord record = recordList.iterator().next();

			ImageView img = ButterKnife.findById(recordView, R.id.id_home_item_icon_img);
			TextView name = ButterKnife.findById(recordView, R.id.id_home_item_name);
			TextView time = ButterKnife.findById(recordView, R.id.id_home_item_time);
			TextView desc = ButterKnife.findById(recordView, R.id.id_home_item_desc);
			TextView user = ButterKnife.findById(recordView, R.id.id_home_item_user);

			name.setText(record.getName());
			desc.setText(record.getDesc());
			SimpleDateFormat formatDay = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
			time.setText(formatDay.format(record.time()));

			//审核人&操作人
			if (record.getArrangeInfoList().iterator().next().getVerifier() != null) {

				String userName = record.getArrangeInfoList().iterator().next().getVerifier().getUserName();
				user.setText("审核人：" + userName);

			} else {

				String userName = record.getArrangeInfoList().iterator().next().getFromUser().getUserName();
				user.setText("操作人：" + userName);

			}

			ArrangeRecordType type = ArrangeRecordType.getType(record.getType());

			if (ArrangeRecordType.arrange.equals(type)) {

				img.setImageResource(R.drawable.ic_arrange_record_arrange);

			} else if (ArrangeRecordType.arrange_cancel.equals(type)) {

				img.setImageResource(R.drawable.ic_arrange_record_arrange);

			} else if (ArrangeRecordType.exchange.equals(type)) {

				img.setImageResource(R.drawable.ic_arrange_record_exchange);

			} else if (ArrangeRecordType.exchange_cancel.equals(type)) {

				img.setImageResource(R.drawable.ic_arrange_record_exchange);

			} else if (ArrangeRecordType.replace.equals(type)) {

				img.setImageResource(R.drawable.ic_arrange_record_exchange);

			} else if (ArrangeRecordType.replace_cancel.equals(type)) {

				img.setImageResource(R.drawable.ic_arrange_record_exchange);

			}

		} else {
			caller.getRecordEmptyView().setVisibility(View.VISIBLE);
			caller.getRecordView().setVisibility(View.GONE);
		}

	}

	/**
	 * 我的排班
	 */
	private void dealMyArrange() {

		List<ArrangeInfo> myArrangeList = page.getArrangeInfoList();
		caller.setMyArrangeList(myArrangeList);

		if (myArrangeList != null && !myArrangeList.isEmpty()) {

			caller.getArrangeEmptyView().setVisibility(View.GONE);
			caller.getArrangeView().setVisibility(View.VISIBLE);

			List<View> myArrangeViews = caller.getMyArranges();

			for (int i = 0; i < myArrangeList.size(); i++) {

				//可见
				myArrangeViews.get(i).setVisibility(View.VISIBLE);

				TextView iconNameView = ButterKnife.findById(myArrangeViews.get(i), R.id.id_home_item_icon_name);
				ViewGroup iconBgView = ButterKnife.findById(myArrangeViews.get(i), R.id.id_home_item_icon_bg);
				ImageView iconImgView = ButterKnife.findById(myArrangeViews.get(i), R.id.id_home_item_icon_img);
				TextView timeView = ButterKnife.findById(myArrangeViews.get(i), R.id.id_home_item_time);
				TextView descView = ButterKnife.findById(myArrangeViews.get(i), R.id.id_home_item_desc);
				TextView userView = ButterKnife.findById(myArrangeViews.get(i), R.id.id_home_item_user);

				ArrangeInfo myArrange = myArrangeList.get(i);
				SimpleDateFormat formatDay = new SimpleDateFormat("yyyy年MM月dd日");
				timeView.setText(formatDay.format(myArrange.getArrangeTypeinfo().start()));
				descView.setText(myArrange.getArrangeTypeinfo().getDuration());
				userView.setVisibility(View.GONE);

				if (myArrange != null) {
					iconNameView.setText(myArrange.getArrangeTypeinfo().getName());
					ImageUtils.load(iconImgView, myArrange.getArrangeTypeinfo().getIcon());
					ViewUtils.setRadiusBg(iconBgView, myArrange.getArrangeTypeinfo().getColor());
				}

			}

		} else {

			caller.getRecordEmptyView().setVisibility(View.VISIBLE);
			caller.getRecordView().setVisibility(View.GONE);

		}

	}

	/**
	 * 小组成员 
	 */
	private void circleMember() {
		List<AccountUser> memberList = page.getUserList();

		if (memberList != null && !memberList.isEmpty()) {

			caller.getUserEmptyView().setVisibility(View.GONE);
			caller.getUserView().setVisibility(View.VISIBLE);

			caller.getUserList().clear();

			if (memberList.size() < 5) {

				caller.getUserList().addAll(memberList);

				//更多选项
				AccountUser addUser = new AccountUser();
				addUser.setUid("-1");//添加成员
				caller.getUserList().add(addUser);

			} else {

				caller.getUserList().addAll(memberList.subList(0, 4));

				//更多选项
				AccountUser addUser = new AccountUser();
				addUser.setUid("-2");//更多
				caller.getUserList().add(addUser);

			}

			HomeMemberAdapter adapter = new HomeMemberAdapter(caller, caller.getUserList(), page.getUserCount());

			caller.getMemberGirdView().setAdapter(adapter);
			caller.getMemberGirdView().setOnItemClickListener(this);

			AccessTokenKeeper tokenKeeper = AccessTokenKeeper.readAccessToken(caller.getActivity());
			if (tokenKeeper.isLogin()) {

				for (AccountUser member : memberList) {

					if (tokenKeeper.getUser().getUid() == member.getUid()) {//每次访问首页，更新当前登陆用户信息

						String accessToken = member.getUid();
						String openId = member.getUid();
						String expiresTime = String.valueOf(Long.MAX_VALUE);

						AccessTokenKeeper newtokenKeeper = new AccessTokenKeeper(accessToken, expiresTime, openId, member);
						AccessTokenKeeper.keepAccessToken(caller.getActivity(), newtokenKeeper);

					}

				}

			}

		} else {

			caller.getUserEmptyView().setVisibility(View.VISIBLE);
			caller.getUserView().setVisibility(View.GONE);

		}

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

		AccountUser user = caller.getUserList().get(position);

		AccessTokenKeeper tokenKeeper = AccessTokenKeeper.readAccessToken(caller.getActivity());
		if (tokenKeeper.isLogin()) {

			if (user.getUid().equals("-1")) {

				int circleId = tokenKeeper.getUser().getCircleList().iterator().next();
				CircleUserAddFragment.go(caller.getActivity(), circleId);

			} else if (user.getUid().equals("-2")) {

				CircleMemberFragment.go(caller.getActivity());

			} else {
				//				ViewUtils.toast("@@@点击用户");

				if (tokenKeeper.isLogin() && tokenKeeper.getUser().getUserType() == UserType.arrange_admin.getValue()) {

					String uid = user.getUid();
					AccountFragment.go(caller.getActivity(), uid);

				}

			}
		}

	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.id_home_arrange_record:

			List<ArrangeRecord> arrangeRecordInfoList = caller.getArrangeRecordInfoList();

			if (arrangeRecordInfoList != null && !arrangeRecordInfoList.isEmpty()) {

				ArrangeRecord record = arrangeRecordInfoList.iterator().next();
				OtherUtils.goToRecordDetails(caller.getActivity(), record);

			}

			break;

		default:
			break;
		}
	}
}
